﻿using System;
using System.ComponentModel.DataAnnotations;
using MoneyBook.Assets.Resources;
using MoneyBook.ComponentModel;
using MoneyBook.Web.Models;
using MoneyBook.Web.Services;
using MoneyBook.Reflection;
using MoneyBook.Web.Assets.Resources;
using System.Linq;

namespace MoneyBook.Views {

    [EnhancePropertyAttributeSources(typeof(Member))]
    public partial class CreateUserViewModel : ViewModelBase {

        [ViewModelProperty]
        private string memberName;

        [ViewModelProperty]
        private string displayName;

        [ViewModelProperty]
        private string password;

        [ViewModelProperty]
        [Display(Name = "RePassword", ResourceType = typeof(Strings))]
        [MapEnhancePropertyAttributeProperties("Password")]
        [CustomValidation(typeof(CreateUserViewModel), "ValidateRePassowrdDifference")]
        private string rePassword;
     
        public void CreateUser() {

            this.ValidateAllProperties();

            if (this.HasErrors) {
                return;
            }

            Member member = new Member() {
                MemberName = this.MemberName,
                DisplayName = this.DisplayName,
                Password = this.Password,
            };

            MembersContext context = new MembersContext();
            context.Members.Add(member);
            context.SubmitChanges(op => {
                if (op.HasError) {
                    this.AddError(op.Error.Message, "MemberName");
                    op.MarkErrorAsHandled();
                    context.Members.Remove(member);
                } else {
                    //TODO:成功メッセージの表示
                }
            }, null);
        }

        public static ValidationResult ValidateRePassowrdDifference(string value, ValidationContext context) {
            CreateUserViewModel model = context.ObjectInstance as CreateUserViewModel;
            if (model == null) {
                //TODO: Exception Message;
                throw new InvalidOperationException();
            }
            if (model.HasError("Password") || model.HasError("RePassword")) {
                return ValidationResult.Success;
            }
            if (value != model.Password) {
                return new ValidationResult(string.Format(Strings.ValidationErrorPropertyValueDifference,
                    Strings.Password, Strings.RePassword));
            }
            return ValidationResult.Success;
        }

        protected override EnhancePropertyAttributeType GetEnhancePtopertyAttributeType() {
            return new EnhancePropertyAttributeType(typeof(CreateUserViewModel));
        }
    }
}
